package com.shuqi.activity;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.RefreshBalanceTask;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.PayModel;
import com.shuqi.model.bean.PayInfo;
import com.shuqi.model.bean.PayModelInfo;

/**
 * 充值
 * 
 * @author chenwei
 * 
 */
public class PayActivity extends ActivityBase implements OnClickListener, IEventListener{

    private final static String TAG = "PayActivity";
    PayInfo mPayInfo = null;// 服务器返回的解析数据

    private LinearLayout mLlError;// 显示网络错误错误的布局
    private TextView mTextRetry;// 网络错误重试
    private CommonTitle mTitle;

    private LinearLayout mLlPay;// 充值首页的整体布局
    private LinearLayout mLlAlipay;// 支付宝支付布局
    private LinearLayout mLlPhone;// 充值卡支付布局
    private LinearLayout mLlGame;// 游戏卡支付布局
    private LinearLayout mLlHints;// 底部提示布局

    private ImageButton mImgAlipay;// 支付宝支付
    private ImageButton mImgPhone;// 充值卡支付
    private ImageButton mImgGame;// 游戏卡支付

    private TextView mTextAlipay;// 支付宝文字
    private TextView mTextPhone;// 充值卡文字
    private TextView mTextGame;// 游戏卡文字
    private TextView mTextBalance;// 余额

    /** 进度圈 */
    private LinearLayout mLayoutLoading;
    private ActivityManager mActivityManager;
    private ToastDialog mLoadingDialog;
    private PayModel mPayModel;

    public final static int PAY_HOME = 0;
    public final static int PAY_HOME_SUCCESS = 1;
    public final static int PAY_HOME_NO_NETWORK = 2;
    public final static int PAY_HOME_INIT = 3;

    private Handler handler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PAY_HOME_INIT:
                    activityLogicForward();
                    break;
                case PAY_HOME_NO_NETWORK:
                    mLlPay.setVisibility(View.GONE);
                    mLlError.setVisibility(View.VISIBLE);
                    mLayoutLoading.setVisibility(View.GONE);
                    break;
                case PAY_HOME:
                    mPayModel.getPayModes();
                    break;
                case PAY_HOME_SUCCESS:
                    mLayoutLoading.setVisibility(View.GONE);
                    activityInitData();
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_pay);

        mActivityManager = ActivityManager.getInstance();
        mPayModel = new PayModel(this);
        mPayModel.addEventListener(this);

        handler.sendEmptyMessage(PAY_HOME_INIT);
    }

    @Override
    public void onEvent(int event, Object data) {
        Log4an.d(TAG, "event:" + event + ",result:" + data);
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                if (data != null) {
                    /*
                     * Message msg = new Message(); msg.what = PAY_HOME_SUCCESS; Bundle d = new
                     * Bundle(); d.putSerializable("mPayInfo", (Serializable) data); msg.setData(d);
                     * handler.sendMessage(msg);
                     */
                    mPayInfo = (PayInfo) data;
                    handler.sendEmptyMessage(PAY_HOME_SUCCESS);
                }
                break;
            default:
                handler.sendEmptyMessage(PAY_HOME_NO_NETWORK);
                break;
        }

    }

    @Override
    public void activityLogicForward() {
        this.mLayoutLoading = (LinearLayout) findViewById(R.id.include_loading);
        mLoadingDialog = new ToastDialog(this);
        
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);

        mLlError = (LinearLayout) findViewById(R.id.include_error);
        mTextRetry = (TextView) findViewById(R.id.retry);
        mTextRetry.setOnClickListener(this);

        mLlPay = (LinearLayout) findViewById(R.id.ll_pay);

        mLlAlipay = (LinearLayout) findViewById(R.id.ll_b_alipay);
        mLlPhone = (LinearLayout) findViewById(R.id.ll_b_phone);
        mLlGame = (LinearLayout) findViewById(R.id.ll_b_game);
        mLlHints = (LinearLayout) findViewById(R.id.ll_hints);

        mTextAlipay = (TextView) findViewById(R.id.tv_b_alipay);
        mTextPhone = (TextView) findViewById(R.id.tv_b_phone);
        mTextGame = (TextView) findViewById(R.id.tv_b_game);
        mImgAlipay = (ImageButton) findViewById(R.id.i_b_alipay);
        mImgPhone = (ImageButton) findViewById(R.id.i_b_phone);
        mImgGame = (ImageButton) findViewById(R.id.i_b_game);
        mTextBalance = (TextView) findViewById(R.id.tv_balance);
        mImgAlipay.setOnClickListener(this);
        mImgPhone.setOnClickListener(this);
        mImgGame.setOnClickListener(this);

        handler.sendEmptyMessage(PAY_HOME);
        this.mLayoutLoading.setVisibility(View.VISIBLE);
    }

    @Override
    public void activityInitData() {
        // Bundle bundle = msg.getData();
        // PayInfo mPayInfo = (PayInfo) bundle.getSerializable("mPayInfo");

        if (PayModel.NET_NEEDLOGIN.equals(mPayInfo.getCode())) {
            LoginActivity.openVerifyForResult(this, LoginActivity.LOGINTYPE_VERIFY);
            finish();
        } else if (PayModel.NET_SUCCESS.equals(mPayInfo.getCode())) {
            mLlPay.setVisibility(View.VISIBLE);
            mLlError.setVisibility(View.GONE);

            mTextBalance.setText(mPayInfo.getBalance() + "");
            List<PayModelInfo> list = mPayInfo.getPayModelInfos();

            for (PayModelInfo info : list) {
                String modeId = info.getModeId();
                String type = info.getType();
                String privilege = info.getPrivilege();

                // 设置type文字
                if ("1".equals(modeId)) {
                    mLlAlipay.setVisibility(View.VISIBLE);
                    mTextAlipay.setText(type);
                } else if ("2".equals(modeId)) {
                    mLlPhone.setVisibility(View.VISIBLE);
                    mTextPhone.setText(type);
                } else if ("3".equals(modeId)) {
                    mLlGame.setVisibility(View.VISIBLE);
                    mTextGame.setText(type);
                }

                // 设置是否优惠
                if ("1".equals(privilege)) {
                    if ("1".equals(modeId)) {
                        setPrivilege(mImgAlipay, modeId);
                    } else if ("2".equals(modeId)) {
                        setPrivilege(mImgPhone, modeId);
                    } else if ("3".equals(modeId)) {
                        setPrivilege(mImgGame, modeId);
                    }
                }
            }

            List<String> hints = mPayInfo.getHintsList();
            for (String hint : hints) {
                View view =
                        LayoutInflater.from(this).inflate(R.layout.pag_item, null,
                                false);
                ((TextView)view.findViewById(R.id.pay_desc)).setText(hint);
                mLlHints.addView(view);
            }
        } else {
            mLoadingDialog.show(false, mPayInfo.getMsg());
        }
    }


    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.retry:
//                if (!Util.isNetworkConnected(this)) {
//                    return;
//                }
//                mLayoutLoading.setVisibility(View.VISIBLE);
//                mLlError.setVisibility(View.GONE);
//                handler.sendEmptyMessage(PAY_HOME);
                
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {

                    @Override
                    public void netErrorCallback() {
                        mLayoutLoading.setVisibility(View.VISIBLE);
                        mLlError.setVisibility(View.GONE);
                        handler.sendEmptyMessage(PAY_HOME);

                    }
                });
                break;
            case R.id.title_left:
                mActivityManager.finishActivity(this);
                break;
            case R.id.i_b_alipay:
                intent = new Intent(this, PayAlipayActivity.class);
                mActivityManager.startNextActivity(intent, this);
                break;
            case R.id.i_b_phone:
                intent = new Intent(this, PayOtherActivity.class);
                intent.putExtra("modeId", "2");
                mActivityManager.startNextActivity(intent, this);
                break;
            case R.id.i_b_game:
                intent = new Intent(this, PayOtherActivity.class);
                intent.putExtra("modeId", "3");
                mActivityManager.startNextActivity(intent, this);
                break;
        }
    }

    /**
     * 优惠活动的icon
     */
    private void setPrivilege(ImageButton view, String modeId) {
        if ("1".equals(modeId)) {
            view.setImageResource(R.drawable.icon_alipay_event);
        } else if ("2".equals(modeId)) {
            view.setImageResource(R.drawable.icon_phone_event);
        } else if ("3".equals(modeId)) {
            view.setImageResource(R.drawable.icon_game_event);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            Log4an.i(TAG, "充值完成，关闭充值首页，并刷新余额...");
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            setResult(Activity.RESULT_OK, intent);
            RefreshBalanceTask.getInstance().refreshBalanceOnline(null);
            finish();
        }
    }

}
